﻿using MediatR;
using PublicCommon;
using T_settlement.Domain;
using T_settlement.Infrastructure.Interfacec;
using T_settlement.Read.API.Application.Command.PayMoneyCommand;

namespace T_settlement.Read.API.Application.CommandHandlers.PayMoneyCommandHandlers
{
    public class GetPayMoneyCommandHandlers:IRequestHandler<GetPayMoneyCommand,PageResult<PayMoney>>
    {
        private readonly IPayMoneyRepository payMoneyRepository;

        public GetPayMoneyCommandHandlers(IPayMoneyRepository payMoneyRepository)
        {
            this.payMoneyRepository = payMoneyRepository;
        }

        public async Task<PageResult<PayMoney>> Handle(GetPayMoneyCommand request, CancellationToken cancellationToken)
        {
            var list = payMoneyRepository.GetAllAsync().Result.Where(x => x.IsDel == false).AsQueryable();

            if (!string.IsNullOrEmpty(request.Outsourcing))
            {
                list = list.Where(x => x.Outsourcing.Contains(request.Outsourcing));
            }

            if (request.PayType != 0 && request.PayType != null)
            {
                list = list.Where(x => x.PayType == request.PayType);
            }

            if (request.CheckState != 0&&request.CheckState!=null)
            {
                list = list.Where(x => x.CheckState == request.CheckState);
            }

            if (!string.IsNullOrEmpty(request.Attn))
            {
                list = list.Where(x => x.Attn.Contains(request.Attn));
            }

            if (!string.IsNullOrEmpty(Convert.ToString(request.BusinessTime)))
            {
                list = list.Where(x => x.BusinessTime == request.BusinessTime);
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
            var res = list.OrderByDescending(x=>x.PayMoneyId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new PageResult<PayMoney>
            {
                PageCount = pageCount,
                TotalCount = totalCount,
                List = res
            };
        }
    }
}
